package com.jeff.tianti.controller;

import com.jeff.tianti.cms.dto.ArticleQueryDTO;
import com.jeff.tianti.cms.dto.ColumnInfoQueryDTO;
import com.jeff.tianti.cms.dto.CurrentArticleInfoDTO;
import com.jeff.tianti.cms.dto.font.ArticleFontQueryDTO;
import com.jeff.tianti.cms.entity.Area;
import com.jeff.tianti.cms.entity.Article;
import com.jeff.tianti.cms.entity.ColumnInfo;
import com.jeff.tianti.cms.service.AreaService;
import com.jeff.tianti.cms.service.ArticleService;
import com.jeff.tianti.cms.service.ColumnInfoService;
import com.jeff.tianti.common.ColumnInfoCom;
import com.jeff.tianti.common.PageBean;
import com.jeff.tianti.common.dto.AjaxResult;
import com.jeff.tianti.common.entity.PageModel;
import com.jeff.tianti.common.util.DateUtils;
import com.jeff.tianti.utils.Constants;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * CMS的Controller
 *
 * @author Jeff Xu
 */
@Controller
@RequestMapping("/cms/api")
@CrossOrigin(maxAge = 3600)
public class CmsController {

    @Autowired
    private ColumnInfoService columnInfoService;
    @Autowired
    private ColumnInfoCom columnInfoCom;
    @Autowired
    private ArticleService articleService;
    @Autowired
    private AreaService areaService;

    /**
     * 获取栏目列表
     *
     * @param request
     * @param
     * @return
     */
    @RequestMapping("/column/list")
    @ResponseBody
    public AjaxResult getColumnList(HttpServletRequest request, HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
        AjaxResult ajaxResult = new AjaxResult();
        String code = request.getParameter("code");
        String name = request.getParameter("name");
        String levelStr = request.getParameter("level");
        String rootColumnId = request.getParameter("rootColumnId");
        //1为true,0为false
        String isRootColumnLikeStr = request.getParameter("isRootColumnLike");
        Integer level = null;
        Boolean isRootColumnLike = false;
        if (StringUtils.isNotBlank(levelStr)) {
            level = Integer.parseInt(levelStr);
        }
        if (StringUtils.isNotBlank(isRootColumnLikeStr) && isRootColumnLikeStr.equals("1")) {
            isRootColumnLike = true;
        }
        ColumnInfoQueryDTO columnInfoQueryDTO = new ColumnInfoQueryDTO();
        columnInfoQueryDTO.setLevel(level);
        columnInfoQueryDTO.setCode(code);
        columnInfoQueryDTO.setName(name);
        columnInfoQueryDTO.setRootColumnId(rootColumnId);
        columnInfoQueryDTO.setIsRootColumnLike(isRootColumnLike);
        List<ColumnInfo> list = this.columnInfoService.queryColumnInfoList(columnInfoQueryDTO);
        ajaxResult.setSuccess(true);
        ajaxResult.setData(list);
        return ajaxResult;
    }

    /**
     * 显示一周快讯
     *
     * @param
     * @param
     * @return
     */
    @RequestMapping(value = "/article/listByWeek", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public AjaxResult getArticleListByWeek(@RequestBody PageBean pageBean) {
        List<Map<String, Object>> list = articleService.findAllByUpdateDateAfter(DateUtils.getDateByBeforDay(new Date(), 50), pageBean).getList();
        return AjaxResult.setSuccessData(list);
    }

    /**
     * 获取文章列表
     *
     * @param request
     * @param
     * @return
     */
    @RequestMapping("/article/list")
    @ResponseBody
    public AjaxResult getArticleList(HttpServletRequest request, HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
        AjaxResult ajaxResult = new AjaxResult();
        String columnId = request.getParameter("columnId");
        //是否分页:1为是，0为否，默认为分页
        String isPage = request.getParameter("isPage");

        //获取前N条的数据
        String topStr = request.getParameter("top");
        String currentPageStr = request.getParameter("currentPage");
        String pageSizeStr = request.getParameter("pageSize");

        int currentPage = 1;
        int pageSize = 10;
        Integer top = null;
        if (StringUtils.isNotBlank(currentPageStr)) {
            currentPage = Integer.parseInt(currentPageStr);
        }
        if (StringUtils.isNotBlank(pageSizeStr)) {
            pageSize = Integer.parseInt(pageSizeStr);
        }
        if (StringUtils.isNotBlank(topStr)) {
            top = Integer.parseInt(topStr);
        }

        PageModel<Article> page = null;
        List<Article> list = null;

        ArticleQueryDTO articleQueryDTO = new ArticleQueryDTO();
        articleQueryDTO.setColumnId(columnId);
        articleQueryDTO.setCurrentPage(currentPage);
        articleQueryDTO.setPageSize(pageSize);
        articleQueryDTO.setTop(top);
        articleQueryDTO.setDeleteFlag(Article.DELETE_FLAG_NORMAL);
        articleQueryDTO.setIsFront(true);
        if (StringUtils.isNotBlank(isPage)) {
            if (isPage.equals("1")) {
                page = this.articleService.queryArticlePage(articleQueryDTO);
                ajaxResult.setData(page);
            } else {
                list = this.articleService.queryArticleList(articleQueryDTO);
                ajaxResult.setData(list);
            }
        } else {
            page = this.articleService.queryArticlePage(articleQueryDTO);
            ajaxResult.setData(page);
        }
        ajaxResult.setSuccess(true);
        return ajaxResult;
    }

//    /**
//     * 获取文章详情
//     *
//     * @param request
//     * @param
//     * @return
//     */
//    @RequestMapping(value = "/article/detail", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @ResponseBody
//    public AjaxResult getArticle(HttpServletRequest request, HttpServletResponse response) {
//        AjaxResult ajaxResult = new AjaxResult();
//        String articleId = request.getParameter("articleId");
//        Map<String, Object> articleMap = null;
//        if (StringUtils.isNotBlank(articleId)) {
//            List<Map<String, Object>> articleList = this.articleService.queryArticleById(articleId);
//            if (!CollectionUtils.isEmpty(articleList)) {
//                articleMap = articleList.get(0);
//            }
//            if (articleMap != null) {
//                Article article = this.articleService.find(articleId);
//                article.setViewCount(article.getViewCount() == null ? 1 : article.getViewCount() + 1);
//                this.articleService.update(article);
//            }
//        }
//        ajaxResult.setSuccess(true);
//        ajaxResult.setData(articleMap);
//        return ajaxResult;
//    }

    /**
     * 获取下一篇文章详情
     *
     * @param request
     * @param
     * @return
     */
    @RequestMapping("/article/next")
    @ResponseBody
    public AjaxResult getNextArticle(HttpServletRequest request, HttpServletResponse response) {
        AjaxResult ajaxResult = new AjaxResult();
        //当前文章ID
        String currentArticleId = request.getParameter("currentArticleId");
        String columnId = request.getParameter("columnId");
        String rootColumnInfoId = request.getParameter("rootColumnInfoId");
        String articleDateStr = request.getParameter("articleDate");
        String orderNoStr = request.getParameter("orderNo");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Article nextArticle = null;
        Date articleDate = null;
        Integer orderNo = null;
        if (StringUtils.isNotBlank(articleDateStr)) {
            try {
                articleDate = sdf.parse(articleDateStr);
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if (StringUtils.isNotBlank(orderNoStr)) {
            orderNo = Integer.parseInt(orderNoStr);
        }
        CurrentArticleInfoDTO currentArticleInfoDTO = new CurrentArticleInfoDTO();
        currentArticleInfoDTO.setColumnId(columnId);
        currentArticleInfoDTO.setArticleId(currentArticleId);
        currentArticleInfoDTO.setArticleDate(articleDate);
        currentArticleInfoDTO.setOrderNo(orderNo);
        if (StringUtils.isNotBlank(columnId)) {
            nextArticle = this.articleService.queryNextArticle(currentArticleInfoDTO);
        }
        ajaxResult.setSuccess(true);
        ajaxResult.setData(nextArticle);
        return ajaxResult;
    }

    /**
     * 获取上一篇文章详情
     *
     * @param request
     * @param
     * @return
     */
    @RequestMapping("/article/pre")
    @ResponseBody
    public AjaxResult getPreArticle(HttpServletRequest request, HttpServletResponse response) {
        AjaxResult ajaxResult = new AjaxResult();
        //当前文章ID
        String currentArticleId = request.getParameter("currentArticleId");
        String columnId = request.getParameter("columnId");
        String articleDateStr = request.getParameter("articleDate");
        String orderNoStr = request.getParameter("orderNo");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Article preArticle = null;
        Date articleDate = null;
        Integer orderNo = null;
        if (StringUtils.isNotBlank(articleDateStr)) {
            try {
                articleDate = sdf.parse(articleDateStr);
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if (StringUtils.isNotBlank(orderNoStr)) {
            orderNo = Integer.parseInt(orderNoStr);
        }
        CurrentArticleInfoDTO currentArticleInfoDTO = new CurrentArticleInfoDTO();
        currentArticleInfoDTO.setColumnId(columnId);
        currentArticleInfoDTO.setArticleId(currentArticleId);
        currentArticleInfoDTO.setArticleDate(articleDate);
        currentArticleInfoDTO.setOrderNo(orderNo);

        if (StringUtils.isNotBlank(columnId)) {
            preArticle = this.articleService.queryPreArticle(currentArticleInfoDTO);
        }
        ajaxResult.setSuccess(true);
        ajaxResult.setData(preArticle);
        return ajaxResult;
    }


    /**
     * 获取 广告法规下的法律法规
     *
     * @param
     * @param
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/adv/law/list", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public AjaxResult getAdvLawList(@RequestBody ArticleFontQueryDTO articleFontQueryDTO) {

        List<ColumnInfo> list = columnInfoCom.getList(Constants.CODE_ADV_LAW);
        List<String> advLawIdList = list.stream().map(columnInfo -> {
            return columnInfo.getId();
        }).collect(Collectors.toList());
        articleFontQueryDTO.setColumnInfoIdList(advLawIdList);
        return AjaxResult.setSuccessPageModelDate(articleService.getArticleSimpleListByColumnInfoIdList(articleFontQueryDTO));
    }


    @ResponseBody
    @RequestMapping(value = "/article/detail", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public AjaxResult getArticleLawDetail(@RequestBody ArticleFontQueryDTO articleFontQueryDTO) {
        PageModel<Map<String, Object>> articleLis = articleService.getArticleListByColumnInfoIdList(articleFontQueryDTO);
        String parentColumnInfoId = articleFontQueryDTO.getParentColumnInfoId();
        if (StringUtils.isNotBlank(parentColumnInfoId)) {
            int totalSize = articleService.countByRootColumnInfoId(parentColumnInfoId);
            articleLis.setTotalCount(totalSize);
            articleLis.setTotalPage(totalSize);
        }
        return AjaxResult.setSuccessPageModelDate(articleLis);
    }

    @ResponseBody
    @RequestMapping(value = "/adv/law/listByParentColumnId", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public AjaxResult advLawListByCode(@RequestBody ArticleFontQueryDTO articleFontQueryDTO) {
        List<ColumnInfo> list = columnInfoCom.getList(Constants.CODE_ADV_LAW);
        List<ColumnInfo> bgtClist = columnInfoCom.getList(Constants.CODE_BGT);
        list.addAll(bgtClist);
        List<String> collect = list.stream().map(columnInfo -> {
            return columnInfo.getId();
        }).collect(Collectors.toList());
        articleFontQueryDTO.setColumnInfoIdList(collect);
        return AjaxResult.setSuccessPageModelDate(articleService.getArticleListByColumnInfoIdList(articleFontQueryDTO));
    }


    @ResponseBody
    @RequestMapping(value = "/adv/article/list", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public AjaxResult getAdvArticleList(@RequestBody ArticleFontQueryDTO articleFontQueryDTO) {
        List<Map<String, Object>> columnIdByCode = columnInfoService.findColumnIdByCode(articleFontQueryDTO.getCode());
        List<String> collect = columnIdByCode.stream().map(columnInfo -> {
            return (String) columnInfo.get("id");
        }).collect(Collectors.toList());
        articleFontQueryDTO.setColumnInfoIdList(collect);
        PageModel<Map<String, Object>> articleListByColumnInfoIdList = articleService.getArticleSimpleListByColumnInfoIdList(articleFontQueryDTO);
        List<Map<String, Object>> list = articleListByColumnInfoIdList.getList();
        list.stream().forEach(map -> {
            if (map.containsKey("adcode")) {
                Object adcode = map.get("adcode");
                if (adcode != null) {
                    Area area = areaService.findByAdcode(adcode.toString());
                    if (area != null) {
                        map.put("city", area.getName());
                    }
                }
            }
        });

        return AjaxResult.setSuccessPageDate(list, articleListByColumnInfoIdList.getTotalPage(), articleListByColumnInfoIdList.getTotalCount());
    }

    @ResponseBody
    @RequestMapping(value = "/adv/article/recommend", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public AjaxResult getArticleRecommendList(@RequestBody ArticleFontQueryDTO articleFontQueryDTO) {
        List<ColumnInfo> list = columnInfoCom.getList(Constants.CODE_HYZX);
        List<String> collect = list.stream().map(columnInfo -> {
            return columnInfo.getId();
        }).collect(Collectors.toList());
        articleFontQueryDTO.setColumnInfoIdList(collect);
        return AjaxResult.setSuccessPageModelDate(articleService.getArticleSimpleListByColumnInfoIdList(articleFontQueryDTO));
    }

}
